using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Identity.Models
{
    public class MyIdentityContext
    {
        private readonly AuthenticationStateProvider _authenticationStateProvider;

        public MyIdentityContext(AuthenticationStateProvider authenticationStateProvider)
        {
            _authenticationStateProvider = authenticationStateProvider;
            _ = InitializeAsync(); // 自动初始化
        }

        public string? UserName { get; private set; }
        public List<string> Roles { get; private set; } = new List<string>();

        public string? DisplayName { get; private set; }

        public string? Icon { get; private set; }
 

        private async Task InitializeAsync()
        {
            var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            if (user.Identity != null && user.Identity.IsAuthenticated)
            {
                UserName = user.Identity.Name;

                // 获取用户的角色
                Roles = user.Claims
                            .Where(c => c.Type == ClaimTypes.Role)
                            .Select(c => c.Value)
                            .ToList();
                DisplayName = user.Claims.FirstOrDefault(c => c.Type == "DisplayName")?.Value ?? "未知";
                Icon=user.Claims.FirstOrDefault(c => c.Type == "Icon")?.Value ?? "未知";
                        
            }
            else
            {
                UserName = null;
                Roles.Clear();
                DisplayName=null;
            }
        }
    }
}